package com.lingyi.algorithm.lab2;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

/**
 * 合并有序链表
 * @author chenweilong
 * @email 1433471850@qq.com
 * @date 2020-08-20 10:03
 */
public class MergeLinkList {

    public static Node<Integer> initNode(Integer ...ints) {

        if (ints.length < 2) {
            System.out.println("长度不能小于2");
        }


        Node<Integer> head = new Node<>();
        head.setT(ints[0]);

        Node<Integer> tail = head;


        for (int i = 1; i < ints.length; i++) {
            Node<Integer> newHead = new Node<>();
            newHead.setT(ints[i]);
            tail.setNext(newHead);
            tail = newHead;
        }
        return head;
    }


    public static void main(String[] args) {

        Node<Integer> node1 = MergeLinkList.initNode(3,5,8,10);
        Node<Integer> node2 = MergeLinkList.initNode(4,9,20,30);

        Node<Integer> newHead = new Node<>();

        Node<Integer> r = newHead;


        Node<Integer> p = node1;
        Node<Integer> q = node2;

        while (p != null && q != null) {
            if (p.getT() < q.getT()) {
                r.setNext(p);
                r = p;
                p = p.getNext();
            }else {
                r.setNext(q);
                r = q;
                q = q.getNext();
            }
        }

        if (p != null) {
            r.setNext(p);
        }else if (q != null) {
            r.setNext(q);
        }

        MergeLinkList.print(newHead);
    }


    public static void print(Node<Integer> head) {
        while (head.getNext() != null) {
            head = head.getNext();
            System.out.println(head.getT());
        }
    }



}
